from PyQt6.QtWidgets import QListWidget,QListWidgetItem,QWidget,QLabel,QAbstractItemView
from PyQt6.QtWidgets import QApplication
from PyQt6.QtCore import QSize,Qt
from PyQt6.QtGui import QImage,QPixmap,QTransform
import sys
import os
import base64
from utils.Logger import LogPrint
from utils.PdfUtils import pdfConvertToPreImage,getPdfImageList
from utils.PdfConvertTask import PdfConvertTask

class PdfPreviewList(QListWidget):


    def __init__(self,parent=None):
        super().__init__(parent=parent)
        self.setStyleSheet("QListWidget::item{height:200px;}")  # 设置每行的高度
        self.setFixedSize(QSize(300,300))
        self.setSpacing(10)
        self.setAcceptDrops(True)
        self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop)
        self.setDefaultDropAction(Qt.DropAction.MoveAction)
        #错误信息回调
        self.errorInfoCallback=None

        #滚动条回调
        self.scrollCallback=None

        #当前显示页面索引
        self.currentPageNoIndex=0

        #加载完成回调
        self.onLoadFinishCallback=None

        self.pageNoList=[]

        #选择文件列表
        self.selectPdfList=[]

        #本地图片目录列表
        self.localImageDirList=[]

        #已转换pdf文件个数
        self.convertPdfCount=0

        # 连接滚动条信号
        self.verticalScrollBar().valueChanged.connect(self.onScroll)

    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
            event.setDropAction(Qt.DropAction.MoveAction)
            super().dropEvent(event)
            event.accept()
        else:
            event.ignore()

    def setErrorInfoCallback(self,callback):
        self.errorInfoCallback=callback


    def setItemClickedCallback(self,callback):
        self.onItemClickedCallback=callback

    def setOnLoadFinishCallback(self,onLoadFinishCallback):
        self.onLoadFinishCallback=onLoadFinishCallback

    #更新当前pdf页面id，滑动滚动条时调用
    def setScrollCallback(self,callback):
        self.scrollCallback=callback

    def loadPdf(self,fileList,pageNoList=None):
        LogPrint.info('fileList',fileList,'pageNoList',pageNoList)
        self.clear()
        totalPageCount=0
        if fileList is not None and len(fileList)>0:
            #初始化变量
            self.selectPdfList.clear()
            self.convertPdfCount=0
            for filePath in fileList:
                LogPrint.debug('filePath',filePath)
                self.selectPdfList.append(filePath)
            #遍历转换文件
            for filePath in fileList:
                LogPrint.debug('filePath',filePath)
                ####
                self.pageNoList.clear()
                if pageNoList and len(pageNoList)>0:                   
                    for pageNo in pageNoList:
                        self.pageNoList.append(pageNo)
                #耗时操作放子任务中
                self.pdfTask=PdfConvertTask(parent=self)
                LogPrint.info('begin startPdfConvertTask')
                self.pdfTask.startPdfConvertTask(filePath,callback=self.afterPdfConvert)

                
        else:
            self.dealErrorInfo('未选择pdf文件')

        return totalPageCount
    
    def afterPdfConvert(self,images,localImgPath):

        #保存本地文件目录

        if self.convertPdfCount==0:
            self.localImageDirList.clear()

        self.localImageDirList.append(localImgPath)
        self.convertPdfCount+=1

        if self.convertPdfCount<len(self.selectPdfList):
            return
        #pdf文件都转换完之后，再做如下逻辑
        totalPageCount=0
        for localImgPath in self.localImageDirList:
            fileList = getPdfImageList(localImgPath)
                    
            fileIndex=1
            for filePath in fileList:
                if self.pageNoList:
                    if fileIndex in self.pageNoList:
                        LogPrint.debug(f'localImgPath:{localImgPath},filePath:{filePath}')
                        self.addImageItem(localImgPath+'/'+filePath)
                        totalPageCount+=1
                                
                else :
                    self.addImageItem(localImgPath+'/'+filePath)
                    totalPageCount+=1
                fileIndex+=1

        if self.onLoadFinishCallback:
            self.onLoadFinishCallback(totalPageCount)
        
    #增加item
    def addImageItem(self, filePath):
        LogPrint.debug(filePath)
        item = QListWidgetItem(self)
        imgLabel=QLabel()
        qImage = QImage(filePath)
        width = qImage.width()
        height = qImage.height()

        #QImage 转为QPixmap
        pix = QPixmap.fromImage(qImage)
        trans = QTransform()
        trans.rotate(0)  # 这里设置旋转角度
        new = pix.transformed(trans)
        # 设置标签宽和高
        pdfShowWidth=250
        pdfShowHeight=int(height*pdfShowWidth/width)
        LogPrint.debug(width,height,pdfShowWidth,pdfShowHeight)
        imgLabel.setFixedSize(pdfShowWidth, pdfShowHeight) #存放pdf 控件大小
        imgLabel.setScaledContents(True)  # 图片缩放
        imgLabel.setPixmap(new)
        item.setSizeHint(QSize(100, pdfShowHeight))
        self.setItemWidget(item, imgLabel)

    #滚动到指定位置
    def scrollToSpecifiedItem(self,index) :
        # 确保索引在有效范围内
        if index >= 0 and index < self.count():
            item = self.item(index)
            self.scrollToItem(item)

    def turnRightPage(self):
        if self.currentPageNoIndex < self.count()-1:
            self.currentPageNoIndex+=1
            self.scrollToSpecifiedItem(self.currentPageNoIndex)
            return self.currentPageNoIndex+1
        return 1
    
    def turnLeftPage(self):
        if self.currentPageNoIndex > 0:
            self.currentPageNoIndex-=1
            self.scrollToSpecifiedItem(self.currentPageNoIndex)
            return self.currentPageNoIndex+1
        return 1
    
    def isTurnLeft(self):
        if self.currentPageNoIndex <= 0:
            return False
        else :
            return True
        
    def isTurnRight(self):
        if self.currentPageNoIndex >= self.count()-1:
            return False
        else :
            return True

    #监听滚动条
    def onScroll(self,value):
        LogPrint.debug(f'value:{value}')
        if self.scrollCallback:
            self.scrollCallback(value)


    def dealErrorInfo(self,content):
        LogPrint.error('PdfPreviewList',content)
        if self.errorInfoCallback:
            self.errorInfoCallback(content)

class Ui_Form(QWidget):
    def __init__(self):
        super(Ui_Form,self).__init__()
        self.setupUi(self)


    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(310, 258)

        self.fileListWidget=PdfPreviewList(parent=Form)

        self.fileListWidget.loadPdf('D:/期末综合复习测试卷.pdf')
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Ui_Form()    
    main.show()    
    #main.showMaximized()
    sys.exit(app.exec())